package org.znxs.znxsframe.services.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.znxs.znxsframe.common.ErrorCode;
import org.znxs.znxsframe.constant.CommonConstant;
import org.znxs.znxsframe.exception.BusinessException;
import org.znxs.znxsframe.exception.ThrowUtils;
import org.znxs.znxsframe.mapper.ChartMapper;
import org.znxs.znxsframe.model.dto.chart.ChartQueryRequest;
import org.znxs.znxsframe.model.entity.Chart;
import org.znxs.znxsframe.services.ChartService;
import org.znxs.znxsframe.utils.SqlUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author administer
 * @description 针对表【chart(图表信息表)】的数据库操作Service实现
 * @createDate 2024-10-15 14:47:28
 */
@Service
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart>
        implements ChartService {

    @Resource
    private ChartMapper chartMapper;

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    @Override
    public Wrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {


        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();
        Long id = chartQueryRequest.getId();
        Long userId = chartQueryRequest.getUserId();
        String name = chartQueryRequest.getName();
        // 拼接查询条件

        queryWrapper.eq(ObjectUtils.isNotEmpty(name), "name", name);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;

    }

    @Override
    public void createUserChartTable(String tableName, List<String> headAttributes) {
        ThrowUtils.throwIf(StrUtil.isBlank(tableName), ErrorCode.PARAMS_ERROR, "表名不能为空");
        ThrowUtils.throwIf(CollUtil.isEmpty(headAttributes), ErrorCode.PARAMS_ERROR, "请求参数为空");
        // 封装属性
        List<Map<String, Object>> params = new ArrayList<>();
        headAttributes.forEach(param -> {
            Map<String, Object> column = new HashMap<>();
            column.put("columnName", param);
            column.put("columnType", "VARCHAR(255)");
            column.put("columnComment", param);
            params.add(column);
        });
        try {
            chartMapper.createUserChartTable(tableName, params);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建用户图表数据表出错" + e.getMessage());
        }

    }

    @Override
    public void insertUserChartTable(String tableName, List<List<String>> rowAttributes) {
        ThrowUtils.throwIf(StrUtil.isBlank(tableName), ErrorCode.PARAMS_ERROR, "表名不能为空");
        ThrowUtils.throwIf(CollUtil.isEmpty(rowAttributes), ErrorCode.PARAMS_ERROR, "请求参数为空");
        // 封装数据
        chartMapper.insertUserChartTable(tableName, rowAttributes);
    }

    @Override
    public boolean handleUpdateChartStatus(long charId, String status) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(charId);
        updateChartResult.setStatus(status);
        return updateById(updateChartResult);
    }

    @Override
    public void handleUpdateChartStatusError(long charId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(charId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(execMessage);
        boolean result = updateById(updateChartResult);
        if (!result) log.error("更新图表失败状态操作失败" + charId + execMessage);
    }
}




